package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;

import com.cloudbroker.bcs.platform.ltb.middle.entity.CouponJournal;
import org.apache.ibatis.session.SqlSession;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.*;

/**
 * Created by xuss13891 on 2016/11/23.
 */
public class Common {

    private static final String POSSIBLE_CHARS="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static final String MAPPER_PATH = "com.cloudbroker.bcs.platform.ltb.middle.dao.";
    /**
     * 生产一个指定长度的随机字符串
     * @param length 字符串长度
     * @return
     */
    public static String generateRandomString(int length) {
        StringBuilder sb = new StringBuilder(length);
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < length; i++) {
            sb.append(POSSIBLE_CHARS.charAt(random.nextInt(POSSIBLE_CHARS.length())));
        }
        return sb.toString();
    }

    /**
     * 获取8位不重复随机码（取当前时间戳转化为十六进制）
     * @param time
     * @return
     */
    public static String toHex(long time){
        return Integer.toHexString((int)time);
    }

    public static Integer getCurrentDate() {
        Calendar c = Calendar.getInstance();//可以对每个时间域单独修改

        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int date = c.get(Calendar.DATE);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);

        return year*10000 + (month + 1) * 100 + date;
    }

    public static Integer getDate(int begin, int duration) {
        Calendar c = Calendar.getInstance();//可以对每个时间域单独修改

        c.set(begin/10000, (begin%10000)/100 - 1, begin%100);
        c.add(Calendar.DATE, duration);

        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int date = c.get(Calendar.DATE);

        return year*10000 + (month + 1) * 100 + date;
    }

    public static Integer getCurrentTime() {
        Calendar c = Calendar.getInstance();//可以对每个时间域单独修改

        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int date = c.get(Calendar.DATE);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);

        return hour*10000 + (minute + 1) * 100 + second;
    }

    public static String sha256(String base) {
        try{
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(base.getBytes("UTF-8"));
            StringBuffer hexString = new StringBuffer();

            for (int i = 0; i < hash.length; i++) {
                String hex = Integer.toHexString(0xff & hash[i]);
                if(hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            return hexString.toString();
        } catch(Exception ex){
            throw new RuntimeException(ex);
        }
    }

    public static void updateStockExpired(SqlSession conn){
        Map<String, Object> mapIn = new HashMap<String, Object>();
        mapIn.put("currentTime", System.currentTimeMillis());
        mapIn.put("currentDate", getCurrentDate());
        conn.update(MAPPER_PATH + "CouponStockMapper.updateExpired");
        conn.commit();
    }

    public static void updateUserExpired(SqlSession conn){
        Map<String, Object> mapIn = new HashMap<String, Object>();
        mapIn.put("currentTime", System.currentTimeMillis());
        mapIn.put("currentDate", getCurrentDate());
        conn.update(MAPPER_PATH + "CouponUserMapper.updateExpired");
        conn.commit();
    }

    public static String nullToEmpty(String str){
        return str == null?" ":str;
    }

    public static Long nullToEmpty(Long l){
        return l == null?0:l;
    }

    public static Integer nullToEmpty(Integer i){
        return i==null?0:i;
    }

    public static Byte nullToEmpty(Byte b){
        return b==null?(byte)0:b;
    }

    public static Float nullToEmpty(Float f){
        return f==null?0:f;
    }

    public static Double nullToEmpty(Double d){
        return d==null?0:d;
    }

    public static String emptyToNull(String str){
        if (str == null || str.isEmpty()){
            return null;
        }
        return str;
    }

    public static final int COUPON_LOCK_INTERVAL = 30 * 60 * 1000;// 锁定时间30分钟

    public static void main(String[] args){
//        Set<String> check = new HashSet<String>();
//
//        //生成2000000个随机字符串，检查是否出现重复
//        for (int i = 0; i < 2000000; i++) {
//            String s = toHex(System.currentTimeMillis());
//            if (check.contains(s)) {
//                System.out.println("Repeated string found : " + s);
//            } else {
//                if (i % 1000 == 0) System.out.println("generated " + i / 1000 + "000 strings.");
//                check.add(s);
//            }
//        }
        System.out.println(getCurrentDate());
        System.out.println(getCurrentTime());
        System.out.println(getDate(getCurrentDate(), 30));
    }
}
